﻿/**
 *	(C) 2014 Yuanjj
 *
 *	define db class
 *
 *	histroy
 * 		2014-07-01	Yuanjj		-	create
 */

#ifndef _DB_H_
#define _DB_H_

#include "define.h"
#include "include.h"
#include "typedef.h"
#include "routine/threads/base_thread.h"

/**
 *	thread class
 */
class ping_thread: public vbase_thread
{
	Q_OBJECT

public:
	ping_thread();
	~ping_thread();

public:
    /**
     *	set mysql object
     */
    pem_void_t	set_mysql_obj( MYSQL* condb );

protected:
    MYSQL		*m_condb;

protected:
    /**
     *	thread fun for ping
     */
    virtual pem_void_t		run();
};

/**
 *	class mysql qurey result
 */
class cls_res
{
public:
    cls_res();
    ~cls_res();

protected:
    MYSQL_RES		*m_res;
    MYSQL_ROW		m_row;
    pem_s32_t		m_fnum;		// field count
    pem_s32_t		m_rnum;		// row count

public:
    /**
     *	get field count
     */
    pem_u32_t		get_field_num();

    /**
     *	get next row
     */
    pem_bool_t		get_next_row();

    /**
     *	get bool data
     */
    pem_bool_t 		get_data_bool( pem_s32_t index, pem_s8_t* truetext, pem_u32_t size );

    /**
     *	get string data
     */
    pem_void_t 		get_data_string( pem_s32_t index, pem_s8_t* pdata, pem_u32_t size );

    /**
     *	get usnigned int data
     */
    pem_u32_t 		get_data_int( pem_s32_t index );

    /**
     *	free res
     */
    pem_void_t		free_res();

public:
    /**
     *	over load operator "="
     */
    cls_res&		operator=( MYSQL_RES* res );

    /**
     *	over load operator "=="
     */
    pem_bool_t		operator==( MYSQL_RES* res );
};

/**
 *	cls_db class
 */
class cls_db
{
public:
    cls_db();
    ~cls_db();

protected:
    MUTEX_LOCK		m_lock;
    MYSQL			m_condb;

protected:
    ping_thread		m_ping;

public:
    /**
     *	initialize the data base object
     */
    pem_error_t		instance();

    /**
     *	release the data base object
     */
    pem_void_t		release();

    /**
     *	lock and unlock
     */
    pem_void_t		lock()		{ _LOCK( &m_lock ); }
    pem_void_t		unlock()	{ _UNLOCK( &m_lock ); }

public:
    /**	query sql */
    pem_error_t			query( const pem_s8_t* sql );

    /** get error text */
    const pem_s8_t*		get_error();

    /** get query result */
    pem_error_t			get_res( cls_res& sqlres );

protected:
    /**
     *	connect to mysql database
     */
    pem_error_t		_connect_mysql( pem_s8_t* host, pem_s8_t* user, pem_s8_t* passwd, pem_s8_t* db, pem_u16_t port );

    /**
     *	set character set
     */
    pem_error_t		_set_character_set( pem_s8_t* name );

    /**
     *	close connect
     */
    pem_void_t		_close_connect();
};

#endif // _DB_H_
